package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import com.sky.service.UserOrderReminderService;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserOrderReminderServiceImpl implements UserOrderReminderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 客户催单
     * @param id 订单id
     */
    @Override
    public void reminder(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 判断订单是否存在
        if (orders == null) {
            // 订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 封装提交数据
        Map<String, Object> map = new HashMap<>();
        /**
         * 包含字段
         * type：1表示来单提醒，2表示客户催单
         * orderId：订单id
         * content：提醒内容
         */
        // 1表示来单提醒，2表示客户催单
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber() + " 用户催单");

        // 通过WebSocket向客户端浏览器发送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
